package com.wm.blog_gateway.auth;

import com.alibaba.fastjson.JSONObject;
import com.wm.blog_common.constatnt.CommonConstant;
import com.wm.blog_common.result.Result;
import com.wm.blog_gateway.config.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;

/***
 * @ClassName: AuthSuccessHandler
 * @Description: 校验成功
 * @Author: 半卷流年
 * @Create_time: 18:43 2020-3-30
 */
@Component
public class AuthSuccessHandler implements ServerAuthenticationSuccessHandler {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        //登录成功,返回用户jwt token
        String token = CommonConstant.TOKEN_PREFIX + " " + jwtTokenUtil.generateToken(principal);
        ServerHttpResponse response = webFilterExchange.getExchange().getResponse();
        response.setStatusCode(HttpStatus.OK);
        Result<String> result = Result.success();
        result.setData(token);
        String body = JSONObject.toJSONString(result);
        DataBuffer buffer = null;
        try {
            buffer = response.bufferFactory().wrap(body.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return response.writeWith(Mono.just(buffer));
    }
}
